import mqtt from 'mqtt'

// MQTT配置
const MQTT_CONFIG = {
  host: 'localhost',
  port: 8083, // WebSocket端口
  path: '/mqtt',
  clientId: `shelife_client_${Math.random().toString(16).substr(2, 8)}`,
  username: '',
  password: '',
  keepalive: 60,
  reconnectPeriod: 1000,
  connectTimeout: 30 * 1000
}

// MQTT客户端
let mqttClient = null
let isConnected = false
let messageCallbacks = {}

// 初始化MQTT客户端
export const initMqttClient = () => {
  if (mqttClient && isConnected) {
    console.log('MQTT客户端已连接')
    return Promise.resolve(mqttClient)
  }

  return new Promise((resolve, reject) => {
    try {
      // 创建MQTT客户端连接
      const options = {
        clientId: MQTT_CONFIG.clientId,
        username: MQTT_CONFIG.username,
        password: MQTT_CONFIG.password,
        keepalive: MQTT_CONFIG.keepalive,
        reconnectPeriod: MQTT_CONFIG.reconnectPeriod,
        connectTimeout: MQTT_CONFIG.connectTimeout,
        clean: true
      }

      // 使用WebSocket连接
      const url = `ws://${MQTT_CONFIG.host}:${MQTT_CONFIG.port}${MQTT_CONFIG.path}`
      mqttClient = mqtt.connect(url, options)

      mqttClient.on('connect', () => {
        console.log('MQTT客户端连接成功')
        isConnected = true
        resolve(mqttClient)
      })

      mqttClient.on('error', (error) => {
        console.error('MQTT连接错误:', error)
        isConnected = false
        reject(error)
      })

      mqttClient.on('close', () => {
        console.log('MQTT连接关闭')
        isConnected = false
      })

      mqttClient.on('reconnect', () => {
        console.log('MQTT重新连接中...')
      })

      mqttClient.on('offline', () => {
        console.log('MQTT客户端离线')
        isConnected = false
      })

      mqttClient.on('message', (topic, message) => {
        console.log(`收到消息 - 主题: ${topic}, 内容: ${message.toString()}`)
        handleMqttMessage(topic, message)
      })
    } catch (error) {
      console.error('初始化MQTT客户端失败:', error)
      reject(error)
    }
  })
}

// 处理MQTT消息
const handleMqttMessage = (topic, message) => {
  try {
    const messageData = JSON.parse(message.toString())
    
    // 查找对应的回调函数
    if (messageCallbacks[topic]) {
      messageCallbacks[topic].forEach(callback => {
        try {
          callback(messageData)
        } catch (error) {
          console.error('执行MQTT消息回调失败:', error)
        }
      })
    }
  } catch (error) {
    console.error('解析MQTT消息失败:', error)
  }
}

// 订阅主题
export const subscribeTopic = (topic, callback) => {
  if (!mqttClient || !isConnected) {
    console.error('MQTT客户端未连接')
    return false
  }

  if (!messageCallbacks[topic]) {
    messageCallbacks[topic] = []
  }

  messageCallbacks[topic].push(callback)

  mqttClient.subscribe(topic, { qos: 1 }, (err) => {
    if (err) {
      console.error(`订阅主题失败: ${topic}`, err)
      return false
    }
    console.log(`成功订阅主题: ${topic}`)
    return true
  })
}

// 取消订阅主题
export const unsubscribeTopic = (topic, callback) => {
  if (!mqttClient || !isConnected) {
    console.error('MQTT客户端未连接')
    return false
  }

  if (messageCallbacks[topic]) {
    if (callback) {
      // 移除特定回调
      messageCallbacks[topic] = messageCallbacks[topic].filter(cb => cb !== callback)
    } else {
      // 移除所有回调
      delete messageCallbacks[topic]
    }
  }

  mqttClient.unsubscribe(topic, (err) => {
    if (err) {
      console.error(`取消订阅主题失败: ${topic}`, err)
      return false
    }
    console.log(`成功取消订阅主题: ${topic}`)
    return true
  })
}

// 发布消息
export const publishMessage = (topic, message, options = {}) => {
  if (!mqttClient || !isConnected) {
    console.error('MQTT客户端未连接')
    return Promise.reject(new Error('MQTT客户端未连接'))
  }

  return new Promise((resolve, reject) => {
    try {
      const messageStr = typeof message === 'string' ? message : JSON.stringify(message)
      const publishOptions = {
        qos: 1,
        ...options
      }

      mqttClient.publish(topic, messageStr, publishOptions, (err) => {
        if (err) {
          console.error(`发布消息失败: ${topic}`, err)
          reject(err)
        } else {
          console.log(`成功发布消息 - 主题: ${topic}, 内容: ${messageStr}`)
          resolve()
        }
      })
    } catch (error) {
      console.error('发布消息异常:', error)
      reject(error)
    }
  })
}

// 断开MQTT连接
export const disconnectMqtt = () => {
  if (mqttClient && isConnected) {
    mqttClient.end(false, () => {
      console.log('MQTT连接已断开')
      isConnected = false
      messageCallbacks = {}
    })
  }
}

// 获取连接状态
export const getMqttConnectionStatus = () => {
  return isConnected
}

// 默认导出
export default {
  initMqttClient,
  subscribeTopic,
  unsubscribeTopic,
  publishMessage,
  disconnectMqtt,
  getMqttConnectionStatus
}